package com.eystar.ext.kit;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieKit {
	public static final int COOKIE_DEFAULT_MAX_AGE = 3600 * 24 * 7;

	/**
	 * 销毁Cookie
	 * 
	 * @param request
	 * @param cookieName
	 * @param response
	 */
	public static void removeCookie(HttpServletRequest request, HttpServletResponse response, String cookieName) {
		Cookie cookie = getCookieByName(request, cookieName);
		if (cookie != null) {
			cookie.setValue(null);
			cookie.setMaxAge(0);// 立即销毁cookie
			cookie.setPath("/");
			response.addCookie(cookie);
		}
	}

	/**
	 * 销毁all Cookie
	 * 
	 * @param request
	 * @param cookieName
	 * @param response
	 */
	public static void removeAllCookie(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Cookie> cookieMap = ReadCookieMap(request);
		for (Entry<String, Cookie> e : cookieMap.entrySet()) {
			removeCookie(request, response, e.getKey());
		}
	}

	/**
	 * 添加或修改cookie
	 * 
	 * @param request
	 * @param response
	 * @param cookieName
	 * @param cookieValue
	 */
	public static void addCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
			String cookieValue, int maxAge) {
		Cookie cookie = getCookieByName(request, cookieName);
		if (cookie != null) {
			cookie.setMaxAge(maxAge);// 立即销毁cookie
			cookie.setPath("/");
		} else {
			cookie = new Cookie(cookieName, cookieValue);
			cookie.setMaxAge(maxAge);
			cookie.setPath("/");
		}
		response.addCookie(cookie);
	}

	/**
	 * 添加或修改cookie, 生命周期默认一周
	 * 
	 * @param request
	 * @param response
	 * @param cookieName
	 * @param cookieValue
	 */
	public static void addCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
			String cookieValue) {
		addCookie(request, response, cookieName, cookieValue, COOKIE_DEFAULT_MAX_AGE);
	}

	/**
	 * 根据名字获取cookie
	 * 
	 * @param request
	 * @param name
	 *            cookie名字
	 * @return
	 */
	public static Cookie getCookieByName(HttpServletRequest request, String name) {
		Map<String, Cookie> cookieMap = ReadCookieMap(request);
		if (cookieMap.containsKey(name)) {
			Cookie cookie = (Cookie) cookieMap.get(name);
			return cookie;
		} else {
			return null;
		}
	}

	/**
	 * 将cookie封装到Map里面
	 * 
	 * @param request
	 * @return
	 */
	public static Map<String, Cookie> ReadCookieMap(HttpServletRequest request) {
		Map<String, Cookie> cookieMap = new HashMap<String, Cookie>();
		Cookie[] cookies = request.getCookies();
		if (null != cookies) {
			for (Cookie cookie : cookies) {
				cookieMap.put(cookie.getName(), cookie);
			}
		}
		return cookieMap;
	}
}
